import { resolve } from 'path'
import KoaRouter from 'koa-router'
import glob from 'glob'
import R from 'ramda'
import {resolvePath, changeToArr, convert} from '../utils/common'
import {log} from './api'

const pathPrefix = Symbol('pathPrefix')         // 防止前缀属性被重写或覆盖

const routeMap = []

export class Route {
    constructor(app, routesPath) {
        this.app = app
        this.router = new KoaRouter()
        this.routesPath = routesPath
    }

    init = () => {
        const { app, router, routesPath } = this

        glob.sync(resolve(routesPath, './*/*.js')).forEach(require)

        R.forEach(
            ({target, method, path, callback}) => {
                const prefix = resolvePath(target[pathPrefix])
                router[method](prefix + path, ...callback)
            }
        )(routeMap)

        app.use(router.routes())
        app.use(router.allowedMethods())
    }
}

export const setRouter = method => path => (target, key, descriptor) => {
    routeMap.push({
        target,
        method,
        path: resolvePath(path),
        callback: changeToArr(target[key])
    })
    return descriptor
}

export const Get = setRouter('get')

export const Post = setRouter('post')

export const Put = setRouter('put')

export const Delete = setRouter('delete')


export const apiController = path => target => (target.prototype[pathPrefix] = `/api${resolvePath(path)}`)

export const adminController = path => target => (target.prototype[pathPrefix] = `/admin${resolvePath(path)}`)

export const Log = convert(log)